package com.ruoyi.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.AuditStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.crm.domain.CrmExpertPool;
import com.ruoyi.crm.domain.CrmOrderCollectPayMoney;
import com.ruoyi.crm.domain.CrmProject;
import com.ruoyi.crm.domain.dto.CrmProjectDTO;
import com.ruoyi.crm.mapper.*;
import com.ruoyi.crm.service.ICrmExpertPoolService;
import com.ruoyi.crm.service.ICrmProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 项目Service业务层处理
 *
 * @author yanwenliang
 * @date 2024-08-16
 */
@Service
public class CrmProjectServiceImpl extends ServiceImpl<CrmProjectMapper, CrmProject> implements ICrmProjectService {
    @Autowired
    private CrmProjectMapper crmProjectMapper;

    @Autowired
    private CrmTaskMapper crmTaskMapper;

    @Autowired
    private ICrmExpertPoolService crmExpertPoolService;

    @Autowired
    private CrmOrderCollectPayMoneyMapper crmOrderCollectPayMoneyMapper;

    @Autowired
    private CrmOrderPayDetailsMapper crmOrderPayDetailsMapper;

    @Autowired
    private CrmOrderCollectDetailsMapper crmOrderCollectDetailsMapper;

    /**
     * 查询项目
     *
     * @param projectId 项目主键
     * @return 项目
     */
    @Override
    public CrmProject selectCrmProjectByProjectId(String projectId) {
        return crmProjectMapper.selectCrmProjectByProjectId(projectId);
    }

    /**
     * 查询项目列表
     *
     * @param crmProject 项目
     * @return 项目
     */
    @Override
    public List<CrmProjectDTO> selectCrmProjectList(CrmProject crmProject) {
        if (!SecurityUtils.hasAdmin()) {
            crmProject.setUserId(SecurityUtils.getUserId());
        }
        List<CrmProjectDTO> crmProjects = crmProjectMapper.selectCrmProjectList(crmProject);

        crmProjects.forEach(item -> {
            BigDecimal actualDay = crmTaskMapper.getActualDay(item.getOrderId(), item.getCustomerId(),item.getUserId());
            item.setActualTaskCount(ObjectUtil.isNull(actualDay) ? BigDecimal.ZERO : actualDay);
            //查询收付款 审核通过的
            List<CrmOrderCollectPayMoney> collectPayMonies = crmOrderCollectPayMoneyMapper.selectList(new LambdaQueryWrapper<CrmOrderCollectPayMoney>()
                    .eq(CrmOrderCollectPayMoney::getOrderId, item.getOrderId())
                    .eq(CrmOrderCollectPayMoney::getCustomerId, item.getCustomerId())
                    .eq(CrmOrderCollectPayMoney::getAuditStatus, AuditStatus.PASS.getCode()));
            // 收款未付
            BigDecimal collectDetailsAmounts = getCollectMoneyByCollectPayMonies(collectPayMonies);
            item.setAwaitCollection(collectDetailsAmounts != null ? collectDetailsAmounts : BigDecimal.ZERO);

            // 付款未付
            BigDecimal payDetailsAmounts = getPayMoneyByCollectPayMonies(collectPayMonies);
            item.setAccountAmt(payDetailsAmounts != null ? payDetailsAmounts : BigDecimal.ZERO);



        });
        return crmProjects;
    }

    private BigDecimal getCollectMoneyByCollectPayMonies(List<CrmOrderCollectPayMoney> collectPayMonies) {
        if (StringUtils.isNotEmpty(collectPayMonies)) {
            Map<String, List<CrmOrderCollectPayMoney>> map = collectPayMonies.stream().collect(Collectors.groupingBy(CrmOrderCollectPayMoney::getMoneyType));
            //收款容器
            List<CrmOrderCollectPayMoney> collectList = map.get("1");
            if (StringUtils.isNotEmpty(collectList)) {
                List<String> ids = collectList.stream().map(CrmOrderCollectPayMoney::getCollectPayMoneyId).collect(Collectors.toList());
                return crmOrderCollectDetailsMapper.getCollectMoney(ids);
            }
        }
        return BigDecimal.ZERO;
    }

    private BigDecimal getPayMoneyByCollectPayMonies(List<CrmOrderCollectPayMoney> collectPayMonies) {

        if (StringUtils.isNotEmpty(collectPayMonies)) {
            Map<String, List<CrmOrderCollectPayMoney>> map = collectPayMonies.stream().collect(Collectors.groupingBy(CrmOrderCollectPayMoney::getMoneyType));
            //付款容器
            List<CrmOrderCollectPayMoney> payList = map.get("0");
            if (StringUtils.isNotEmpty(payList)) {
                List<String> ids = payList.stream().map(CrmOrderCollectPayMoney::getCollectPayMoneyId).collect(Collectors.toList());
                return crmOrderPayDetailsMapper.getPayMoney(ids);
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * 新增项目
     *
     * @param crmProject 项目
     * @return 结果
     */
    @Override
    public int insertCrmProject(CrmProject crmProject) {

        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<CrmProject>().eq(CrmProject::getCustomerId, crmProject.getCustomerId()).eq(CrmProject::getOrderId, crmProject.getOrderId()));

        if (count > 0) {
            throw new ServiceException("该客户下已存在该商机的项目!");
        }

        crmProject.setCreateTime(DateUtils.getNowDate());
        crmProject.setCreateBy(SecurityUtils.getUsername());
        crmProject.setUserId(SecurityUtils.getUserId());
        crmProject.setProjectId(IdWorker.getIdStr());
        return crmProjectMapper.insert(crmProject);
    }

    /**
     * 修改项目
     *
     * @param crmProject 项目
     * @return 结果
     */
    @Override
    public int updateCrmProject(CrmProject crmProject) {
        crmProject.setUpdateTime(DateUtils.getNowDate());
        return crmProjectMapper.updateCrmProject(crmProject);
    }

    /**
     * 批量删除项目
     *
     * @param projectIds 需要删除的项目主键
     * @return 结果
     */
    @Override
    public int deleteCrmProjectByProjectIds(Long[] projectIds) {
        return crmProjectMapper.deleteCrmProjectByProjectIds(projectIds);
    }

    /**
     * 删除项目信息
     *
     * @param projectId 项目主键
     * @return 结果
     */
    @Override
    public int deleteCrmProjectByProjectId(Long projectId) {
        return crmProjectMapper.deleteCrmProjectByProjectId(projectId);
    }


    /**
     * 查询自己负责的项目
     *
     * @param crmProject
     * @return
     */
    @Override
    public List<CrmProjectDTO> getCrmProjectListByUser(CrmProject crmProject) {

        String username = SecurityUtils.getUsername();

        CrmExpertPool crmExpertPool = new CrmExpertPool();
        crmExpertPool.setExpertName(username);
        crmExpertPool.setIsExternal("0");
        CrmExpertPool expertOne = crmExpertPoolService.getExpertOne(crmExpertPool);

        crmProject.setSearchValue(SecurityUtils.getUsername());

        if (!SecurityUtils.hasAdmin()) {
            // 运维、开发、负责人没有值时，走单独的查询条件
            if (!StringUtils.isAnyEmpty(crmProject.getDevUserId(), crmProject.getOpsUserId(), crmProject.getCreateBy())
                    && ObjectUtils.isEmpty(crmProject.getCustomerId()) && ObjectUtils.isEmpty(crmProject.getOrderId())) {
                crmProject.setSearchFlag("0");
            }

            // 不是专家库成员时，判定为销售
            if (ObjectUtils.isEmpty(expertOne)) {
                if (StringUtils.isEmpty(crmProject.getCreateBy())) {
                    crmProject.setCreateBy(SecurityUtils.getUsername());
                }
            } else {
                String expertId = expertOne.getExpertId();
                String expertType = expertOne.getExpertType();
                if (StringUtils.isEmpty(crmProject.getOpsUserId()) && "1".equals(expertType)) {
                    crmProject.setOpsUserId(expertId);
                } else if (StringUtils.isEmpty(crmProject.getDevUserId()) && "0".equals(expertType)) {
                    crmProject.setDevUserId(expertId);
                }
            }
        }

        List<CrmProjectDTO> crmProjectDTOList = crmProjectMapper.selectCrmProjectList(crmProject);
        crmProjectDTOList.forEach(item->{
            BigDecimal actualDay = crmTaskMapper.getActualDay(item.getOrderId(), item.getCustomerId(),item.getUserId());
            item.setMyTaskCount(actualDay);
        });

        return crmProjectDTOList;
    }
}
